package com.wondertek.poms.sync.manager.mixed;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wondertek.poms.core.utils.OutHttpUtil;
import com.wondertek.poms.dao.po.PrdCont;
import com.wondertek.poms.dao.po.PrdInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * 混编工作台通知工具类
 * 地址是系统动态加载的
 *
 * @author douzi
 */
@Slf4j
@Component
public class MixedHttpUtils {
    @Autowired
    private OutHttpUtil outHttpUtil;

    public void mixedCharge(PrdCont pc, PrdInfo pi) {
        mixedCharge(pc, pi, "MIXED_URL_CHARGE_1301", "1301");
    }

    public void mixedBc(PrdCont pc, PrdInfo pi) {
        mixedCharge(pc, pi, "MIXED_URL_BC_1401", "1401");
    }

    public void mixedPublish(PrdCont pc, PrdInfo pi) {
        mixedCharge(pc, pi, "MIXED_URL_PUBLISH_1302", "1302");
    }

    public void mixedCharge(PrdCont pc, PrdInfo pi, String key, String type) {
        if (null == pc) {
            log.info("通知混编工作台时节目为null");
            return;
        }
        try {
            //20191008 douzi 新增混编对接
            String mixedUrl = outHttpUtil.findByKey(key);
            if (StringUtils.isBlank(mixedUrl)) {
                log.info("混编工作台通知|节目Id:" + pc.getPrdContId() + "|内容Id:" + pc.getContentId() + "没有配置发送url|key:" + key + "|type:" + type);
                return;
            }

            MixedSendData sendData = new MixedSendData(pc, pi, type);
            MixedHttpUtils.doPost(mixedUrl, sendData, "code", "0");
        } catch (Exception e) {
            log.info("混编工作台通知报错|节目Id:" + pc.getPrdContId() + "|媒资Id:" + pc.getMmsId() + "|内容Id:" + pc.getContentId(), e);
        }
    }

    public static boolean doPost(String url, Object params, String successValue, String successAttr) {
        String json = JSON.toJSONString(params);
        boolean flag = false;
        for (int i = 0; i < 2; i++) {
            String result = httpPost(url, json);
            if (StringUtils.isNotBlank(result)) {
                JSONObject jo = JSONObject.parseObject(result);
                log.info("混编工作台通知工具类===入参为:" + json + "第  " + i + "  次http请求==返回值:" + jo.getString(successValue));
                if (successAttr.equals(jo.getString(successValue))) {
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }

    public static String httpPost(String url, String json) {
        PostMethod method = new PostMethod(url);
        HttpClient httpClient = new HttpClient();
        try {
            HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
            managerParams.setConnectionTimeout(10000);
            managerParams.setSoTimeout(10000);
            RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8");
            method.setRequestEntity(entity);
            int statusCode = httpClient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                log.error("HttpClient Error==[入参:" + json + "][statusCode = " + statusCode + "]");
                return "";
            }
            InputStream in = method.getResponseBodyAsStream();
            StringBuffer sb = new StringBuffer();
            InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
            char[] b = new char[4096];
            for (int n; (n = isr.read(b)) != -1; ) {
                sb.append(new String(b, 0, n));
            }
            String returnStr = sb.toString();
            return returnStr;
        } catch (Exception e) {
            log.error("====混编工作台通知工具类的URL失败======url|{}|json|{}", url, json);
            e.printStackTrace();
//			e.getStackTrace();
        } finally {
            method.releaseConnection();
        }

        return "";
    }
}
